//
//  DrawTrailerTableViewController.m
//  JxCarios
//
//  Created by xcq on 15/2/3.
//  Copyright (c) 2015年 xiongchuanqi. All rights reserved.
//

#import "DrawTrailerTableViewController.h"
#import "DrawTrailerTableViewCell.h"
#import "DrawTrailerDetailViewController.h"
#import "RegionSeletedViewController.h"
static BOOL regionSelete = NO;
static NSString *cellDrawStr = @"DrawTrailer";
@implementation DrawTrailerTableViewController

- (void) viewDidLoad{
    [super viewDidLoad];
    self.tableView.hidden = YES;
    self.dic_type = @"pullcar";
    _currenPage = 1;
    [self initAbout];
    [self initWithData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.view.window hideToastActivity];
}
- (void)initWithData{
    if ([Common currenCity] && [[Common currenCity] customObjectForkey:@"location"]) {
        _location.latitude = [[[[Common currenCity] customObjectForkey:@"location"] customObjectForkey:@"lat"] doubleValue];
        _location.longitude = [[[[Common currenCity] customObjectForkey:@"location"] customObjectForkey:@"lon"] doubleValue];
        [self netRequest:_location andRresh:NO];
        [self setRightBtnTitle];
        return;
    }
    if (!self.locService) {
        self.locService = [[LocationGetObj alloc] init];
    }
    self.locService.delegate = self;
    [self.locService startLocation];
}


- (void)netRequest:(CLLocationCoordinate2D )location andRresh:(BOOL)bol{
    if (!self.carAround) {
        self.carAround = [CarAroundDataSource dataSourceWithRequestor:self];
    }
    self.carAround.lat = [NSString stringWithFormat:@"%f",_location.latitude];
    self.carAround.lon = [NSString stringWithFormat:@"%f",_location.longitude];
    self.carAround.dic_type = self.dic_type;
    self.carAround.page = [NSString stringWithFormat:@"%ld",_currenPage];
    [self.carAround carAroundInfo:^(id result) {
        _tableDataSource = [NSMutableArray arrayWithArray:[result objectForKey:@"sellerlist"]];
        _countPage = [[result objectForKey:@"totalpages"] integerValue];
        self.tableView.hidden = NO;
        [self.tableView reloadData];
    }anfFail:^(id result) {
        _currenPage --;
        [self.tableView footerEndRefreshing];
    }];
}

- (void)footerRresh {
    if (_countPage <= _currenPage) {
        [self.view.window makeToast:@"没有更多数据了哦"];
        [self.tableView footerEndRefreshing];
        return;
    }
    _currenPage ++;
    self.carAround.lat = [NSString stringWithFormat:@"%f",_location.latitude];
    self.carAround.lon = [NSString stringWithFormat:@"%f",_location.longitude];
    self.carAround.dic_type = self.dic_type;
    self.carAround.page = [NSString stringWithFormat:@"%ld",_currenPage];
    [self.carAround carAroundInfo:^(id result) {
            [_tableDataSource addObjectsFromArray:[result objectForKey:@"sellerlist"]];
            [self.tableView footerEndRefreshing];
            [self.tableView reloadData];
    }anfFail:^(id result) {
            _currenPage --;
            [self.tableView footerEndRefreshing];
    }];
        
 }


- (void)regionSeleteAction:(NSDictionary *)info {
    _currenPage = 1;
    _countPage = 0;
    [_rightBtn setTitle:[info customObjectForkey:@"city"] forState:UIControlStateNormal];
    _location.latitude = [[info customObjectForkey:@"LAT"] floatValue];
    _location.longitude = [[info customObjectForkey:@"LON"] floatValue];
    [self netRequest:_location andRresh:NO];
    [self.tableView scrollRectToVisible:CGRectMake(0, 0, [RextExtends getScreenFrame].size.width, [RextExtends getScreenFrame].size.height) animated:YES];

}

- (void)getLocationSuccess:(BMKUserLocation *)userLocation{
    
    _location = userLocation.location.coordinate;
    [self netRequest:_location andRresh:NO];
    BMKReverseGeoCodeOption *geo = [[BMKReverseGeoCodeOption alloc] init];
    geo.reverseGeoPoint = _location;
    self.locService.geoDelegate = self;
    BOOL ret = [self.locService startReverseGeoCode:geo];
    if (!ret) {
        [self.locService startReverseGeoCode:geo];
    }
    [self.locService stopLocation];
 }

- (void)onGetReverseGeoCodeResultSuccess:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    NSMutableDictionary *dic = [NSMutableDictionary new];
    [dic setObject:result.addressDetail.district forKey:@"district"];
    [dic setObject:result.addressDetail.city forKey:@"city"];
    [dic setObject:result.addressDetail.province forKey:@"province"];
    NSDictionary *location = @{@"lat":@(result.location.latitude),@"lon":@(result.location.longitude)};
    [dic setObject:location forKeyedSubscript:@"location"];
    [Common setCurrenCity:dic];
    if(_rightBtn.titleLabel.text.length > 0) {
        return;
    }
    [self setRightBtnTitle];
 
 }

- (void)onGetGeoCodeResultSuccess:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    if(_rightBtn.titleLabel.text.length > 0) {
        return;
    }
    [self setRightBtnTitle];}

- (void)setRightBtnTitle {
        NSDictionary *dic = [Common currenCity];
        if (!dic) {
            [_rightBtn setTitle:[dic customObjectForkey:@"定位失败"] forState:UIControlStateNormal];
            return;
        }
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightBtn setFrame:CGRectMake(15, 5.0f, 60, 30)];
        [_rightBtn setTitle:[dic customObjectForkey:@"city"] forState:UIControlStateNormal];
        [_rightBtn addTarget:self action:@selector(changeVcShowView:) forControlEvents:UIControlEventTouchUpInside];
        [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _rightBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
}


- (void)initAbout{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.title = @"拖车";
    [self.tableView addFooterWithTarget:self action:@selector(footerRresh)];
    REGISTCELL(@"DrawTrailerTableViewCell", cellDrawStr);
    self.tableView.tableFooterView = [UIView new];
    [self showNavBarWithRightTitle:nil andRightAction:nil andLeftAction:@selector(navigationLeftBtnAction) andCustom:NO];
 
}



- (void)navigationLeftBtnAction{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

//TODO:跳转地址选择
- (void)changeVcShowView:(UIButton *)btn{
    RegionSeletedViewController *selete = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"regionSeleted"];
    selete.target = self;
    selete.action = @selector(regionSeleteAction:);
    [self.navigationController pushViewController:selete animated:YES];
}

#pragma mark - tableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _tableDataSource.count <= 0 ? 0 : _tableDataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DrawTrailerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellDrawStr forIndexPath:indexPath];
    cell.superType = NSStringFromClass([self class]);
    cell.info = [_tableDataSource objectAtIndex:indexPath.row];
    [cell.praiseView removeGestureRecognizer:cell.tap];
//    if (cell.priceLabel.hidden) {
//          cell.shopMz.frame = CGRectMake(cell.shopMz.frame.origin.x,cell.shopMz.frame.origin.y, cell.shopMz.frame.size.width + 42, cell.shopMz.frame.size.height);
//    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  
    DrawTrailerDetailViewController *detail = [[DrawTrailerDetailViewController alloc] init];
    detail.shopId = [[_tableDataSource objectAtIndex:indexPath.row] customObjectForkey:@"ID"];
    detail.distance = [[_tableDataSource objectAtIndex:indexPath.row] customObjectForkey:@"SFZ"];
    [detail netRequest];
    [self.navigationController pushViewController:detail animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 88;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
